package com.example.customview.silder

import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.base.BaseFragment
import com.android.baselibrary.utils.getModel
import com.example.customview.R
import com.example.customview.BR
import com.example.customview.arouter.CustomArouter
import com.example.customview.databinding.TravelActivitySearchCityBinding
import com.example.customview.databinding.TravelLayoutHeaderCityBinding
import com.example.customview.removeItemDecorations


/**
 * Created by  you
 * Date: 2022/7/8
 * Time: 10:56
 * 添加行程点-搜索城市
 */
@Route(path = CustomArouter.CUSTOM_INDEX_BAR)
class SearchCityActivity: BaseFragment<TravelActivitySearchCityBinding>() {

    @JvmField
    @Autowired(name = "currentCity")
    var mCurrentCity = "北京市"
    private var provinceAdapter: SingleRecycleAdapter? = null
    private val cityList = arrayListOf<ProvinceDtoItem>()
    private val mModel by lazy {
        getModel(SearchCityModel::class.java)
    }

    override fun getLayoutID() = R.layout.travel_activity_search_city


    override fun initView() {
        initCurrentCity()
        registerObserve()


        val onItemClickListener = fun(_: View, item: Any) {
            val item = item as ProvinceDtoItem
            val intent = Intent()
            intent.putExtra("cityCode", item.provinceCode)
            intent.putExtra("cityName", item.provinceName)


        }
        provinceAdapter = SingleRecycleAdapter(
            R.layout.travel_item_city_adapter,
            BR.item,
            mItemClickListener = onItemClickListener
        )
        mBinding.recyclerView.adapter = provinceAdapter
        mBinding.viewModel = mModel
        mBinding.lifecycleOwner = this


        mBinding.side.setOverlayTextView(mBinding.tvCityCenter)
            .setOnIndexChangedListener { index, _ ->
                val layoutManager = mBinding.recyclerView.layoutManager as LinearLayoutManager
                val position = getHotCityPosition(index)
                if (position == -1)
                    return@setOnIndexChangedListener
                layoutManager.scrollToPositionWithOffset(position, 0)
            }

        mModel.queryCityListByLocal(context!!, true)
        mBinding.tvBack.setOnClickListener {

        }
    }



    private fun registerObserve() {
        mModel.provinceList.observe(this, Observer {
            if (it.isNullOrEmpty())
                return@Observer
            if (mBinding.recyclerView.itemDecorationCount > 0) {
                mBinding.recyclerView.removeItemDecorationAt(0)
            }
            mBinding.recyclerView.addItemDecoration(ProvinceCityItemDecoration(requireContext(), 38, 1, it, true))
            mModel.cityData.postValue(it)
            cityList.clear()
            cityList.addAll(it)
        })
        mModel.queryCity.observe(this,Observer{
            if (TextUtils.isEmpty(it)) {
                mBinding.llEmptyCity.visibility = View.GONE
                mBinding.recyclerView.visibility = View.VISIBLE
                mModel.cityData
                    .postValue(null)
                mModel.queryCityListByLocal(requireContext(), true)
                return@Observer
            }
            val values = cityList.filter { item ->
                item.provinceName?.contains(it) == true || item.letter?.contains(it, true) == true
            }
            values.forEach {item->
                val pinYin = PinYinUtils.getPinYin(item.provinceName)
                item.letter = pinYin
            }
            val list = values.sortedBy { item->item.letter?.substring(0,1) }

            if(list.isNullOrEmpty()){
               mBinding.llEmptyCity.visibility = View.VISIBLE
                mBinding.recyclerView.visibility = View.GONE
                mModel.cityData.postValue(null)
            }else{
                mBinding.llEmptyCity.visibility = View.GONE
                mBinding.recyclerView.visibility = View.VISIBLE
                mModel.cityData.postValue(list)
                mBinding.recyclerView.removeItemDecorations()
                mBinding.recyclerView.addItemDecoration(ProvinceCityItemDecoration(requireContext(), 38, 1, list, true))


            }

        })
    }

    private fun initCurrentCity(){
        val cityBinding =
            TravelLayoutHeaderCityBinding.inflate(layoutInflater, mBinding.recyclerView, false)
        mBinding.viewModel = mModel
        mBinding.lifecycleOwner = this
        cityBinding.tvCurrentCity.text = mCurrentCity
        mBinding.recyclerView.addHeaderView(cityBinding.root)
    }
    /**
     * 字母列表拖动获取集合对应索引
     * @param letter 字母
     * @return 返回索引
     */
    private fun getHotCityPosition(letter: String): Int {
        val data = mModel.cityData.value ?: return 0
        var position = 0
        data.forEachIndexed { index, cityBean ->
            if (cityBean.letter?.startsWith(letter,true) == true) {
                position = index
                return index + 1
            }
        }
        return position
    }

}